package com.jhws.business.local.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.card.bo.TblCardPerms;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.db.BaseDao;
import com.jhws.util.GsonUtil;
import com.jhws.util.LogHelper;
import com.jhws.util.net.JhHttpClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class CardPermsSynchService {
    @Resource
    private BaseDao BaseDao;

    public void saveCardPerms(TblCardPerms cardPerms) {
        cardPerms.setIsSynch(LocalConstant.SYNCH_STATE_YES);
        BaseDao.saveOrUpdate(cardPerms);
    }

    public void deleteCardPerms(TblCardPerms cardPerms) throws Exception {
        BaseDao.delete(cardPerms);
    }

    public List<TblCardPerms> findCardPermsWhere(String whereStr) throws Exception {
        return BaseDao.findList("from TblCardPerms " + whereStr);
    }

    public void mergeCardPerms(String serverUrl, String commCode, Map<String, String> headers) throws Exception {
        List<TblCardPerms> list = findCardPermsWhere("where is_synch != '" + LocalConstant.SYNCH_STATE_YES + "' and devBuildingNo like '" + commCode + "%'");
        if (list == null || list.isEmpty()) {
            return;
        }
        JhHttpClient hp = new JhHttpClient();
        for (TblCardPerms cardPerms : list) {
            try {
                String s = hp.postJson(serverUrl + "api/localSynch/cardPerms/cardPerms", GsonUtil.toJson(cardPerms), headers);
                LogHelper.d("-------------->     " + s);
                JsonRespData respData = JSON.parseObject(s, JsonRespData.class);
                if (respData.ret_code > 0) {
                    if (cardPerms.getIsSynch() == LocalConstant.SYNCH_STATE_NO) {
                        saveCardPerms(cardPerms);
                    } else if (cardPerms.getIsSynch() == LocalConstant.SYNCH_STATE_DEL) {
                        deleteCardPerms(cardPerms);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
